<?php
/**
 * Created by PhpStorm.
 * User: KaZeline
 * Date: 15-5-12
 * Time: 下午3:01
 * 已取消的订单
 */
ob_start();
// if ($_SESSION['memberID']==1 && $_SESSION['dtype']==9) {
if (($_SESSION['sdtype']==9 && strpos($_SESSION['qx'],'orderReport') )|| $_SESSION['memberID']==1) {
    header('location:admin/orderReport.html');
    exit;
}
include("common/header.html");
include('common/autoload.php');
$out_html = ob_get_contents();
ob_end_clean();

if($_SERVER['HTTP_REQUEST_TYPE']=='getTicket'){
    $sql='SELECT id,title FROM uu_jq_ticket WHERE landid='.($_GET['landid']+0);//
    $GLOBALS['le']->query($sql);
    $tickes = array();
    while($row=$GLOBALS['le']->fetch_assoc()){
        $tickes[]=$row;
    }
    if(count($tickes)){
        echo json_encode(array('s'=>'success','content'=>$tickes));
    }else{
        echo json_encode(array('s'=>'fail'));
    }
    exit;
}
$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = SoapInit::GetSoapInside();
$memberID=$_SESSION['sid'];
if(!$_GET['begintime'] && !$_GET['endtime'])
    goto one;
$btime=$_GET['begintime']?trim($_GET['begintime']):date("Y-m-d",strtotime('-7days'));
$etime=$_GET['endtime']?trim($_GET['endtime']):date("Y-m-d");
$btime = strpos($btime,":")!==false?$btime : $btime." 00:00:00";
$etime = strpos($etime,":")!==false?$etime : $etime." 23:59:59";

$by=$_GET['by']?$_GET['by']:"lid";
$arrID = ($by!='lid' && $by!='tid') ? (string)$row->UUbuyid:(string )$row->{$UUby};
switch ($_GET['by']) {
	case 'mid':
        $arrID = 'UUmid';
        $title = 'UUdname';
		break;
    case 'aid':
        $arrID = $title =  'UUaid';
        break;
    case 'tid':
        $arrID = 'UUtid';
        $title = 'UUttitle';
        break;
	default:
        $arrID = 'UUlid';
        $title = 'UUltitle';
		break;
}
$lid=$_GET['landid']+0;

if(isset($_REQUEST['ticket'])){
    $t = explode("_",$_REQUEST['ticket']);
    $option['tid']=$t[0];
}
switch ($_GET['tjs']) {
	case '2':
        $oname = $_GET['txt'];
		break;
    case '3':
        $otel = $_GET['txt'];
        break;
	default:
		$orderid = $_GET['txt'];
		break;
}
switch ($_GET['aom']) {
    case 'aid':
        $x = simplexml_load_string(
            $s->Order_Globle_Search(
                "",$_GET['fid'], "", "", "", "", "$btime", "$etime", "", "",
                "", "", "$orderid", "$oname", "$otel", "", "", "", "", "",
                0, 9999, 0, 0, "", 0, "", 0, "", "",
                $_SESSION['sid'], 0, 0, 0, ""),
            'SimpleXMLElement',LIBXML_COMPACT
        );
    break;

    default:
        $x = simplexml_load_string(
            $s->Order_Globle_Search(
                "",$_SESSION['sid'], "", "", "", "", "$btime", "$etime", "", "",
                "", "", "$orderid", "$oname", "$otel", "", "", "", "", "",
                0, 9999, 0, 0, "", 0, "", 0, "", "",
                $_GET['aid'], 0, 0, 0, ""),
            'SimpleXMLElement',LIBXML_COMPACT
        );
        break;
}
foreach ($x->Rec as $k => $v) {
    $total_money = $v->UUtprice * $v->UUtnum;
    if((int)$v->UUpmod!=3 && (int)$v->UUtprice * (int)$v->UUtnum == (int)$v->UUtotalmoney)
        //只选晒被取消的和有撤改的订单
        continue;
    ++$result[(int)$v->{$arrID}]['order'];
    $result[(int)$v->{$arrID}]['title'] = (string)$v->{$title};
    $pmode = (int)$v->UUpmode;
    if((int)$v->UUpmod==3){//已取消的订单 全部统计
        $result[(int)$v->{$arrID}]['tnum'] += (int)$v->UUtnum;
        $result[(int)$v->{$arrID}]['money'] += (int)$v->UUtotalmoney;
        $result[(int)$v->{$arrID}]['pmode'.$pmode] += (int)$v->UUtotalmoney;
    }else{//撤改订单只统计撤改了几张
        $num = (int)$v->UUtprice==0 ? 5:(int)$v->UUtotalmoney/(int)$v->UUtprice;//初始票数
        $result[(int)$v->{$arrID}]['tnum'] += ($num - (int)$v->UUtnum);
        $result[(int)$v->{$arrID}]['money'] += ($num - (int)$v->UUtnum)*(int)$v->UUtprice;
        $result[(int)$v->{$arrID}]['pmode'.$pmode] += ($num - (int)$v->UUtnum)*(int)$v->UUtprice;
    }
}

//取供应商名称
if($title=='UUaid'){
    $memberNames = require dirname(__FILE__) . '/module/link_product/Member.cache.php';
    foreach ($result as $k => $v) {
        $result[$k]['title'] = $memberNames[$k];
    }
}
one:
//取景区名字
include("/var/www/html/new/d/class/Member.php");
$m = new Member($s,$memberID);
$sale = $m->salePros();
foreach($sale as $v){
    if(!$land[$v['lid']])
        $land[$v['lid']]= $v['title'];
}
//取分销商名字
include 'getDistors.php';
if($_SESSION['dtype']==7){
    $DistorsNames_aid = getAll($GLOBALS['le'],$memberID);
}else{
    $DistorsNames_aid = getRetail($GLOBALS['le'],$memberID);
}
//取供应商名字


$DistorsNames_mid = getDistors($GLOBALS['le']);

echo $out_html;
//print_r($result);
?>
<script src="js/Calendar.js" type="text/javascript"></script>
<script type="text/javascript" src="js/global/Date_func.js"></script>
<script src="js/jsorder.js"></script>
<script src="http://www.12301.cc/js/WdatePicker.js"></script>
<script type="text/javascript">
    var tableToExcel = (function() {
        var uri = 'data:application/vnd.ms-excel;base64,'
            , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
            , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
            , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
        return function(table, name) {
            if (!table.nodeType) table = document.getElementById(table)
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
            window.location.href = uri + base64(format(template, ctx))
        }
    })()
</script>
<link rel="stylesheet" type="text/css" href="css/member.css"/>
<style>
	.report{margin:10px 0; padding:15px; border:1px solid #eee}
.report span.part{ margin-right:20px;}
	input.time{    background: url("images/rili.png") no-repeat scroll right center #FFFFFF;
    border: 1px solid #7F9DB9;
    height: 20px;
    line-height: 20px;
    width: 150px;}
	.total{ width:100%; text-align:center;}
	input.checkbox{ vertical-align:-2px; margin-right:2px;}
	.btn{ background:#eee; padding:4px 15px; *padding:4px 8px; background:url("images/mc_title.png") no-repeat right top; color:#fff; border:none; cursor:pointer}
	#excel{margin-left:10px;}
</style>
<h3 class="mc_title">
	<span class="mctit_1 notcur"">
		<a href="orderReport.html"><span class="mctit_2">已卖出产品报表</span></a>
	</span>
	<?if($_a->checkAuth("buyOrderReport.html")){?>
    <span class="mctit_1 notcur"">
		<a href="buyOrderReport.html"><span class="mctit_2">已买到产品报表</span></a>
	</span>
<?}else if($_SERVER['SCRIPT_URI']== 'http://www.12301.cc/buyOrderReport.html'){
    exit;//没有权限看这个页面的人 (单纯的分销商) 还是可以通过输入网址到这里
}
    if($_GET['alli']){
        ?>
        <span class="mctit_1 <?=($from=="alliance")?"":"notcur"?>">
		<a href="allianceOrderReport.html"><span class="mctit_2">已卖出联盟产品报表</span></a>
	</span>
    <?}?>
<?if($_SESSION['sid']==1229){?>
    <span class="mctit_1 notcur">
		<a href="orderReport_Compass.html"><span class="mctit_2">数据罗盘</span></a>
	</span>
<?}?>
    <span class="mctit_1">
		<a href="orderReport_Compass.html"><span class="mctit_2">取消的订单报表</span></a>
	</span>
</h3>
<form class="report" method="get">
    <input type="hidden" name="proList" value='<?=$proList?>'/>
    <input type="hidden" name="act" id="act" value=""/>
    <p>
		<span class="part">下单时间:
			<input type="text" name="begintime" id="begintime" class="time" value="<?=$_GET['begintime']?>" onFocus="WdatePicker({startDate:'%y-%M-01 00:00:00',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true})"/>
			<label>至</label>
			<input type="text" name="endtime" id="endtime" class="time" value="<?=$_GET['endtime']?>" onFocus="WdatePicker({startDate:'%y-%M-01 23:59:59',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true})"/>
			<a href="javascript:changeDate('today');" class="sDate">今天</a>
			<a href="javascript:changeDate('yesterday');" class="sDate">昨天</a>
			<a href="javascript:changeDate('week');" class="sDate">本周</a>
			<a href="javascript:changeDate('lastweek');" class="sDate">上周</a>
			<a href="javascript:changeDate('month');" class="sDate">本月</a>
			<a href="javascript:changeDate('lastmonth');" class="sDate">上月</a>
		</span>
        <input type="submit" class="btn" value="查 询"/>
        <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="导出到Excel">
    </p>
    <p style="margin:10px 0;">
	<span  class="part">
		统计方式：
		<select name="by">
            -<option value="">统计方式</option>
            <option value="lid" <?=($_REQUEST['by']=="lid")?"selected":""?>>按景区统计</option>
            <option value="tid" <?=($_REQUEST['by']=="tid")?"selected":""?>>按门票统计</option>
            <option value="mid" <?=($_REQUEST['by']=="mid")?"selected":""?>>按分销商统计</option>
        </select>
	</span>
        <span class="lt">查询条件：</span>
        <select class="condSelect controls" name="tjs" id="condSelect">
            <option <?=$_REQUEST['tjs']=="0"?"selected":""?> value="0">订单号</option>
            <option <?=$_REQUEST['tjs']=="2"?"selected":""?> value="2">取票人姓名</option>
            <option <?=$_REQUEST['tjs']=="3"?"selected":""?> value="3">取票人手机</option>
        </select>
        <input id="condInput" type="text" class="condText controls" value="<?=$_REQUEST['txt']?>" name="txt"/>
        <span class="lt">查询类型：</span>
        <select class="condSelect controls" name="aom" >
            <option <?=$_GET['aom']=="aid"?"selected":""?> value="aid">已卖出产品</option>
            <option <?=$_GET['aom']=="mid"?"selected":""?> value="mid">已买到产品</option>
        </select>
    </p>
    <p style="margin:10px 0;">
		<span  class="part">
            景点：
            <select name="landid" id="land">
                <option value="">--选择--</option>
                <?foreach($land as $k => $v):?>
                    <option value="<?=$k?>" <?=($_REQUEST['landid']==$k)?"selected":""?>><?=$v?></option>
                <?endforeach;?>
            </select>
        </span>
		<span  class="part">
            门票：
            <select name="ticket" id="ticket">
                <option value="">--选择--</option>
                <?
                if(isset($_REQUEST['landid']) && !empty($_REQUEST['landid'])){
                    $sql='SELECT id,title FROM uu_jq_ticket WHERE landid='.($_REQUEST['landid']+0);//
                    $GLOBALS['le']->query($sql);
                    $tickes = array();
                    while($row=$GLOBALS['le']->fetch_assoc()){
                        $tickes[]=$row;
                    }
                    if(count($tickes)){
                        $html = '';
                        foreach($tickes as $v){

                            $title= $v['title'];
                            $vs=$v['id'].'_'.$title;
                            if(isset($_REQUEST['ticket']) && !empty($_REQUEST['ticket']) && $_REQUEST['ticket']==$vs){
                                $html.="<option value='{$vs}' selected='selected'>{$title}</option>";
                            }else{
                                $html.="<option value='{$vs}'>{$title}</option>";
                            }
                        }
                        echo $html;
                    }
                }
                ?>
            </select>
        </span>
        <?if(count($DistorsNames_mid)>0){?>
            <span  class="part" id="mid">选择分销商
            <?=$dTypeName?>：<?=GetHtmlSelect($DistorsNames_mid, 'fid', $fid, array('k'=>0,'v'=>'--分销商--'))?>
            </span>
        <?}?>
        <?if(count($DistorsNames_aid)>0){?>
        <span  class="part" id="aid" >选择供应商
            <?=$dTypeName?>：<?=GetHtmlSelect($DistorsNames_aid, 'aid', $aid, array('k'=>0,'v'=>'--供应商--'))?>
            </span>
        <br/>
    <?}?>
    </p>
</form>
<div class="rank">
    <div class="rankcon">
        <table class="ranktab" id='testTable'>
            <thead id="rankhd">
            <th>序号</th>
            <th style="text-align:left" class="tL"><?=$titleT[$by]?></th>
            <th><span style="position:relative; left:-40px;" class="sort" onclick="sortTable('offmain',2, true ,this);">订单数量</span></th>
            <th><span class="sort" onclick="sortTable('offmain',3, true ,this);">门票数量</span></th>
            <th><span class="sort" onclick="sortTable('offmain',4, true ,this);">金额</span></th>
            <th><span class="sort" onclick="sortTable('offmain',5, true ,this);">余额支付</span></th>
            <th><span class="sort" onclick="sortTable('offmain',6, true ,this);">在线支付</span></th>
            <th><span class="sort" onclick="sortTable('offmain',7, true ,this);">授信支付</span></th>
            <th><span class="sort" onclick="sortTable('offmain',8, true ,this);">产品自销</span></th>
            <th><span class="sort" onclick="sortTable('offmain',8, true ,this);">现场支付</span></th>
            </thead>
            <tbody id="offmain">
            <? if(count($result)){
            foreach($result as $lid=>$row){
            if(empty($row['order'])) continue;
            $totals['order']+=$row['order'];
            $totals['tnum']+=$row['tnum'];
            $totals['money']+=$row['money']/100;
            $totals['pmode0']+=$row['pmode0']/100;
            $totals['pmode1']+=$row['pmode1']/100;
            $totals['pmode2']+=$row['pmode2']/100;
            $totals['pmode3']+=$row['pmode3']/100;
            $totals['pmode4']+=$row['pmode4']/100;
            ?>
            <tr>
                <td><?=++$n?></td>
                <td class="tL"><?=$row['title']?></td>
                <td><?=$row['order']?></td>
                <td><?=$row['tnum']?></td>
                <td><?=$row['money']/100?></td>
                <td><?=$row['pmode0']/100?></td>
                <td><?=$row['pmode1']/100?></td>
                <td><?=$row['pmode2']/100?></td>
                <td><?=$row['pmode3']/100?></td>
                <td><?=$row['pmode4']/100?></td>
            </tr>
            <?}}?>
            <tfoot>
            <?if(count($result)>0){?>
                <tr>
                    <td  colspan="2">总计：</td>>
                    <td><?=$totals['order']?></td>
                    <td><?=$totals['tnum']?></td>
                    <td><?=$totals['money']?></td>
                    <td><?=$totals['pmode0']?></td>
                    <td><?=$totals['pmode1']?></td>
                    <td><?=$totals['pmode2']?></td>
                    <td><?=$totals['pmode3']?></td>
                    <td><?=$totals['pmode4']?></td>
                </tr>
            <?}else{?>
                <tr>
                    <td align="left" colspan="9">&nbsp;&nbsp;&nbsp;交易日期无销售订单！</td>
                </tr>
            <?}?>
            </tfoot>
        </table>
    </div>
</div>
<script>
    $("#time").change(function(){
        Date_func.selectDate($(this).val(),$("#begintime").get(0),$("#endtime").get(0));
    });
    $("input.btn").click(function(){
        var btime=$("#begintime").val();
        var etime=$("#endtime").val();
        btime=btime.split("-");
        etime=etime.split("-");
        month=(etime[0]-btime[0])*12+(etime[1]-btime[1]);
        if(month>3){
            alert("交易日期时间间隔不能超过三个月");
            return false;
        }
    });

    $("#land").change(function(){

        landid=$(this).val();
        if(landid==''){
            _options = '<option value="">--选择--</option>';
            $("#ticket").html(_options);
            return;
        }
        $.ajax({
            uri:window.location.href,
            data:"landid="+landid,
            beforeSend:function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("request_type","getTicket");
            },
            success: function(data){
                data = JSON.parse(data);
                if(data.s=='success'){
                    _options = '<option value="">--选择--</option>';
                    for(var i in data.content){
                        _options+='<option value="'+data.content[i].id+'_'+data.content[i].title+'">'+data.content[i].title+'</option>';
                    }
                    $("#ticket").html(_options);

                }
            }
        });
    });
    function changeDate(date){
        // lastweek颠倒了
        if(date=='lastweek'){
            Date_func.selectDate(date,$("#endtime").get(0),$("#begintime").get(0));
        }else{
            Date_func.selectDate(date,$("#begintime").get(0),$("#endtime").get(0));
        }
    }
</script>